/*
 * @Author: 杨玉龙 
 * @Email undefined 
 * @Date: 2018-10-11 15:55:47 
 * @Last Modified by: 杨玉龙
 * @Last Modified time: 2018-10-11 15:56:08
 * @Document 项目启动文件 [✔️] [✘]
 */

import configInterface from '../interface/configInterface';
import Kao from "koa";
const app = new Kao();
import koaSession from "koa-session";
import bodyParser from "koa-bodyparser";
import convert from 'koa-convert';
import CSRF from 'koa-csrf';
import cors from 'koa2-cors';
import logs from './log';
import views from 'koa-views';
import koaStatic from 'koa-static';
import appRoute from './router';
// mongodb 链接
import mongoose  from './db/mongo';
import paginateMiddleware from "../middleware/paginate";
import authCheckMiddleware from "../middleware/authCheck";

app.keys = ['9D7D0BEC5ECB00C3230B7B51CC3CA625'];
const SESSION_CONFIG = {
    key: 'koa:sess',
    maxAge: 86400000,
    autoCommit: true, /** (boolean) automatically commit headers (default true) */
    overwrite: true, /** (boolean) can overwrite or not (default true) */
    httpOnly: true, /** (boolean) httpOnly or not (default true) */
    signed: true, /** (boolean) signed or not (default true) */
    rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
    renew: true, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
};

// use session
app.use(convert(koaSession(SESSION_CONFIG, app)));
app.use(bodyParser());
app.use(new CSRF({
    invalidSessionSecretMessage: 'Invalid session secret',
    invalidSessionSecretStatusCode: 403,
    invalidTokenMessage: 'Invalid CSRF token',
    invalidTokenStatusCode: 403,
    excludedMethods: ['GET', 'HEAD', 'OPTIONS'],
    disableQuery: false
}));
// 跨域设置
app.use(cors({
    origin: function (ctx) {
        return ctx.header.origin;
    },
    // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'PUT', 'POST', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
// 权限判定中间件
app.use(authCheckMiddleware);
// 注入分页中间件
app.use(paginateMiddleware);
// 静态文件处理
app.use(koaStatic(`${global['BASE_PATH']}/../public/`));
// 视图文件
app.use(convert(views(`${global['BASE_PATH']}/../views/`, { extension: 'ejs' })));
// 路由
app.use(convert(appRoute()));

// 500
app.on('error', async (ctx, err) => {
    logs.error('server error', err, ctx);
    // await ctx.render('50x');
});

// 404
app.use(async (ctx) => {
    if (404 == ctx.status) {
        await ctx.render('home/404');
    }
});

export default async function(config:configInterface) {
    global['mongoose'] = await mongoose();
    global['config'] = config;
    app.listen(config.port);
    console.info(`[✔️]服务启动成功, 开始监听${config.port}端口\r\n`);
};
